suppressMessages(library(COGugaison))
suppressPackageStartupMessages(library(tidyverse))

mortality_period_municipality_level <- function(Municipality_data, start_date, end_date) {
  Municipality_data %>%
    filter(as.numeric(JourDécès) != 0) %>% # excluding 15238 death records
    filter(AnnéeDécès != "") %>% # Filtering what is actually population data
    mutate(Death_date = lubridate::ymd(paste(AnnéeDécès, MoisDécès, JourDécès, sep = "/"))) %>%
    filter(Death_date >= start_date) %>%
    filter(Death_date <= end_date) %>%
    group_by(Municipality_code) %>%
    summarise(NbDeath = n())
}

create_municipality_code_converter <- function(Municipality_idx, Municipality_code) {
  dict <- Municipality_code %>%
    unique() %>%
    setNames(Municipality_idx %>% unique())
  conversion_function <- function(x) {
    sapply(x, function(xi) dict[xi])
  }
  return(conversion_function)
}

create_municipality_code_converter2 <- function(Municipality_idx, Municipality_code) {
  dict_idx_to_code <- Municipality_code %>%
    unique() %>%
    setNames(Municipality_idx %>% unique())
  dict_code_to_idx <- Municipality_idx %>%
    unique() %>%
    as.character() %>%
    setNames(Municipality_idx %>% unique())

  dict <- c(dict_idx_to_code, dict_code_to_idx)

  conversion_function <- function(x) {
    x %>%
      as.character() %>%
      sapply(FUN = function(xi) dict[xi])
  }
  return(conversion_function)
}

give_region_slow <- Vectorize(function(Municipality_code) {
  COGugaison::nivsupra(table_entree = tibble(Municipality_code = Municipality_code), nivsupra = "REG")[, 2]
})

get_region_name_from_department_number <- Vectorize(function(department_number) {
  full_code <- department_number %>% paste(., "001", sep = "")
  i <- 1
  res <- give_region_slow(full_code)
  while (!is.character(res) & i < 1000) {
    i <- i + 1

    if (i < 10) {
      full_code <- department_number %>% paste(., "00", i, sep = "")
    } else if (i < 100) {
      full_code <- department_number %>% paste(., "0", i, sep = "")
    } else {
      full_code <- department_number %>% paste(., i, sep = "")
    }
    print(full_code)
    res <- give_region_slow(full_code)
  }
  return(res)
})

departement_code_to_region_dict <- 1:19 %>%
  c(21:95) %>%
  stringr::str_pad(2, pad = "0") %>%
  (function(nn) {
    nn %>%
      get_region_name_from_department_number() %>%
      setNames(nn) %>%
      unlist()
  }) %>%
  c(., list(
    "2A" = "Corse",
    "2B" = "Corse",
    "97" = "DOM/TOM",
    "98" = "Monaco"
  )) %>%
  unlist()

region_from_department <- Vectorize(function(departement_code) {
  departement_code_to_region_dict[departement_code]
})

prune_iterations <- function(chain, final_size = 1000, warmup_prop = 0) {
  nit <- nrow(chain)
  start_it <- round(max(1, nit * warmup_prop))
  it_to_keep <- round(seq(start_it, nit, length.out = final_size))
  return(chain[it_to_keep, ])
}

create_stan_data <- function(full_data) {
  full_data %>%
    (function(df) {
      list(
        NbDeath = df$NbDeath,
        N = length(df$NbDeath),
        covid = df$covid,
        Population = df$Population,
        N_municipalities = length(df$Municipality_code %>% unique()),
        Municipality_code = df$Municipality_idx %>% as.numeric(),
        municipality_label = df$Municipality_idx %>% as.character(),
        Municipality_code_converter = create_municipality_code_converter(df$Municipality_idx, df$Municipality_code)
      )
    })
}
